import './App.less';

import type { MessageInstance } from 'antd/es/message/interface';
import type { ModalStaticFunctions } from 'antd/es/modal/confirm';
import type { NotificationInstance } from 'antd/es/notification/interface';

import { App as antdApp } from 'antd';
import { useEffect } from 'react';
import { RouterProvider, createBrowserRouter } from 'react-router-dom';

import { CenterSpin } from '@/components';

import { mergeUserRoutes } from './router';
import useRouterStore from './stores/router';
import userStore from './stores/user';

let message: MessageInstance;
let notification: NotificationInstance;
let modal: Omit<ModalStaticFunctions, 'warn'>;

const App = () => {
  const staticFunctions = antdApp.useApp();
  message = staticFunctions.message;
  notification = staticFunctions.notification;
  modal = staticFunctions.modal;

  const token = userStore(state => state.token);
  const refreshUser = userStore(state => state.refreshUser);
  const { getUserAuths, loading, userRoutes } = useRouterStore(state => ({
    getUserAuths: state.getUserAuths,
    loading: state.loading,
    userRoutes: state.userRoutes,
  }));

  useEffect(() => {
    const isLogin = window.location.hash === '/login';
    if (!isLogin && token) {
      refreshUser();
      getUserAuths();
    }
  }, [getUserAuths, refreshUser, token]);

  const router = createBrowserRouter(mergeUserRoutes(userRoutes));

  return !loading ? <RouterProvider router={router} /> : <CenterSpin />;
};

export default App;
export { message, modal, notification };
